package com.unionftech.common.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class UploadFileLifecycleObserver(
    private val registry: ActivityResultRegistry,
    private val maxCount: Int
) :
    DefaultLifecycleObserver {
    private var mCallback: ((uri: Uri, type: String) -> Unit)? = null
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    private lateinit var pickPdf: ActivityResultLauncher<Intent?>
    private lateinit var takePhoto: ActivityResultLauncher<Intent>
    private var currentPhotoPath: String? = null

    companion object {
        /**
         * 打开相册
         */
        const val PICK_PHOTO = "pickPhoto"

        /**
         * 打开PDF文件
         */
        const val OPEN_PDF = "openPdf"

        /**
         * 打开相机
         */
        private const val TAKE_PHOTO = "takePhoto"
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        pickMedia =
            registry.register(
                PICK_PHOTO,
                PickImage(maxCount)
            ) { uri ->
                uri?.also { list ->
                    for (item in list) {
                        mCallback?.invoke(item, PICK_PHOTO)
                    }
                }
            }
        pickPdf = registry.register(
            OPEN_PDF, ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val intent = result.data
            if (intent != null && result.resultCode == Activity.RESULT_OK) {
                intent.data?.also { uri ->
                    mCallback?.invoke(uri, OPEN_PDF)
                }
            }
        }
        takePhoto = registry.register(
            TAKE_PHOTO, ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                if (!TextUtils.isEmpty(currentPhotoPath)) {
                    mCallback?.invoke(File(currentPhotoPath!!).toUri(), TAKE_PHOTO)
                }
            }
        }
    }

    fun setResultCallBack(callback: ((uri: Uri, type: String) -> Unit)?) {
        mCallback = callback
    }

    /**
     * 打开相册选取照片
     */
    fun openPickerPhoto() {
        pickMedia.launch(
            PickVisualMediaRequest(
                ActivityResultContracts.PickVisualMedia.SingleMimeType(
                    "*/*"
                )
            )
        )
    }

    /**
     * 选择pdf文件
     */
    fun openPdfDocument() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/pdf"
        }
        pickPdf.launch(intent)
    }

    /**
     * 打开相机进行拍照
     */
    fun takePhoto(context: Context) {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.addCategory(Intent.CATEGORY_DEFAULT)
            var photoFile: File? = null
            try {
                photoFile = createImageFile(context)
                currentPhotoPath = photoFile.absolutePath
            } catch (e: Exception) {
                e.printStackTrace()
            }
            photoFile?.also {
                val uri = FileProvider.getUriForFile(
                    context,
                    context.applicationInfo.packageName + ".common.fileprovider",
                    it
                )
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                takePhoto.launch(takePictureIntent)
            }
        }
    }

    @Throws(IOException::class)
    private fun createImageFile(context: Context): File {
        // 创建唯一的文件名,通过时间戳
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "JPEG_${timeStamp}_"
        // 获取应用专属的图片存储目录
        val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        // 创建临时文件
        val file = File.createTempFile(
            imageFileName,//前缀
            ".jpg",//后缀
            storageDir//目录
        )
        return file
    }
}